import requests
from PySide6.QtCore import QFile, Qt, QUrl, QThread, Signal
from PySide6.QtGui import QPixmap
from PySide6.QtNetwork import QNetworkAccessManager, QNetworkRequest
from PySide6.QtWidgets import QApplication, QWidget, QPushButton, QListWidgetItem, QFileDialog, QProgressDialog
from PySide6.QtUiTools import QUiLoader
from lxml import html
from segmented_util import segment_text

from download_dialog_ui import DownloadDialog

base_url = "https://xuehaiwuya.site"

headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/237.84.2.178 Safari/537.36",
}


class DownloadThread(QThread):
    """
    下载线程
    """
    progress_updated = Signal(int)  # 信号：更新进度
    finished = Signal()  # 信号：下载完成

    def __init__(self, chapters, download_dir, parent=None):
        super().__init__(parent)
        self.chapters = chapters
        self.download_dir = download_dir

    def run(self):
        progress = 0
        for href in self.chapters:
            response = requests.get(f"{base_url}{href}", headers=headers)
            response.encoding = "utf-8"
            tree = html.fromstring(response.text)
            content = tree.xpath(
                "//div[@id='chaptercontent']/text() | //div[@id='chaptercontent']/br/following-sibling::text()"
            )
            content = [text.strip().replace('\u3000', '') for text in content if text.strip()]
            if len(content) >= 2:  # 确保有标题和内容
                with open(f"{self.download_dir}/{content[0]}.txt", "w", encoding="utf-8") as f:
                    segments = segment_text(text=content[1], threshold=0.6)
                    f.write('\n'.join(segments))
            progress += 1
            self.progress_updated.emit(progress)
        self.finished.emit()


class MyWidget:
    def __init__(self):
        # 动态加载 UI 文件
        ui_file = QFile("ui/main.ui")
        ui_file.open(QFile.ReadOnly)
        self.ui = QUiLoader().load(ui_file)
        ui_file.close()

        # 网络请求管理器
        self.network_manager = None

        # 进度条组件
        self.progress_dialog = None

        # 下载线程
        self.download_thread = None

        # 搜索按钮绑定槽
        self.ui.search_btn.clicked.connect(self.search)

        # 搜索结果列表绑定槽
        self.ui.search_result_list_widget.clicked.connect(self.getBookInfo)

        # 整本下载按钮绑定槽
        self.ui.all_download_btn.clicked.connect(self.downloadAll)

        # 章节下载按钮绑定槽
        self.ui.choose_download_btn.clicked.connect(self.downloadChapters)

    def search(self):
        print("search")
        # 拿到用户输入的搜索关键字
        keyword = self.ui.kw_line.text()
        response = requests.get(f"{base_url}/book/search?q={keyword}", headers=headers)
        response.encoding = "utf-8"
        tree = html.fromstring(response.text)
        a_elements = tree.xpath("//div[@class='block']//ul[@class='lis']/li//a")
        result_set = [(a.get('href'), a.text.strip()) for a in a_elements if a.get('href') and a.text]
        for href, text in result_set:
            item = QListWidgetItem(text)
            item.setData(Qt.UserRole, href)
            self.ui.search_result_list_widget.addItem(item)

    def getBookInfo(self):
        print("getBookInfo")
        # 得到用户点击选中的书籍Url
        href = self.ui.search_result_list_widget.currentItem().data(Qt.UserRole)
        response = requests.get(f"{base_url}{href}", headers=headers)
        response.encoding = "utf-8"
        tree = html.fromstring(response.text)

        # 拆出封面图，交给网络请求下载器
        cover_element = tree.xpath("//div[@class='cover']//img")[0]
        img_url = cover_element.get("src")
        self.network_manager = QNetworkAccessManager()

        # 绑定下载器触发的封面图下载的槽
        self.network_manager.finished.connect(self.transCover)

        # 触发下载
        request = QNetworkRequest(QUrl(f"{base_url}{img_url}"))
        self.network_manager.get(request)

        # 书籍信息
        title_element = tree.xpath("//div[@class='book_box']//dl//dt[@class='name']")[0]
        self.ui.book_name_label.setText(title_element.text)
        au_tag_elements = tree.xpath("//div[@class='book_box']//dl//dd[@class='dd_box']//span")
        au_tag_list = [data.text for data in au_tag_elements if data.text]
        # 将作者，标签，章节数显示到对应label上
        self.ui.author_label.setText(au_tag_list[0])
        self.ui.tag_label.setText(au_tag_list[1])
        self.ui.chapter_num_label.setText(au_tag_list[2])

        # 拆出章节信息
        chapter_elements = tree.xpath("//div[@class='book_last']//dl//dd//a")
        chapter_list = [(data.get('href'), data.text.strip()) for data in chapter_elements if data.text]
        # 渲染ListWidget之前先清空之前的数据
        self.ui.chapter_list_widget.clear()
        # 将章节信息设置到ListWidget中
        for href, text in chapter_list:
            item = QListWidgetItem(text)
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setCheckState(Qt.Unchecked)
            item.setData(Qt.UserRole, href)
            self.ui.chapter_list_widget.addItem(item)

    def transCover(self, reply):
        """下载封面图,设置到lable展示"""
        image_data = reply.readAll()
        pixmap = QPixmap()
        pixmap.loadFromData(image_data)
        self.ui.cover_label.setPixmap(pixmap)
        self.ui.cover_label.setScaledContents(True)
        self.ui.cover_label.setMaximumSize(171, 213)

    def downloadAll(self):
        print("downloadAll")
        # 实现整本下载逻辑（可选）
        for index in range(self.ui.chapter_list_widget.count()):
            print(self.ui.chapter_list_widget.item(index).data(Qt.UserRole))


    def downloadChapters(self):
        print("downloadChapters")
        selected_chapters = []
        for index in range(self.ui.chapter_list_widget.count()):
            item = self.ui.chapter_list_widget.item(index)
            if item.checkState() == Qt.Checked:
                chapter_urls = item.data(Qt.UserRole)
                selected_chapters.append(chapter_urls)

        if not selected_chapters:
            print("未选择章节")
            return

        download_dir = self.selectDirectory()
        if not download_dir:
            print("未选择下载目录")
            return

        # 显示进度对话框
        self.show_progress(len(selected_chapters))

        # 启动下载线程
        self.download_thread = DownloadThread(selected_chapters, download_dir, self.ui)
        self.download_thread.progress_updated.connect(self.progress_dialog.update_progress)
        self.download_thread.finished.connect(self.progress_dialog.accept)
        self.download_thread.start()

    def show_progress(self, maximum):
        """显示下载进度"""
        self.progress_dialog = DownloadDialog(max_value=maximum, parent=self.ui)
        self.progress_dialog.show()

    def selectDirectory(self):
        directory = QFileDialog.getExistingDirectory(
            self.ui,
            "选择目录",
            "",
            QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks
        )
        return directory


if __name__ == "__main__":
    app = QApplication()
    w = MyWidget()
    w.ui.show()
    app.exec()
